package preorder

import (
    "time"
	"strconv"
	"dhfshop/controllers/base"
	"dhfshop/models/preorder"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type ResTypeController struct {
	base.BaseController
}

func (this *ResTypeController) List() {
	curRoleId := this.Ctx.Input.GetData("curRoleId").(int)
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	query,_, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if curRoleId == 2 {
	    query["partner_id"] = strconv.FormatInt(partnerId, 10)
	}
	l, cnt, err := preorder.GetAllResTypes(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount  int64                 `json:"total_count"`
		ResTypes []*preorder.ResType `json:"res_types"`
	}{TotalCount: cnt, ResTypes: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *ResTypeController) Post() {
	var v preorder.ResType
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.Name, "name")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	v.PartnerId =int64(this.Ctx.Input.GetData("curCompanyId").(int))
	id, err := preorder.AddResType(&v)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	v.ResTypeId = int64(id)
	rsp := struct {
		ResTypeId  int64 `json:"res_type_id"`
		Modified time.Time `json:"modified"`
	}{ResTypeId: id, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ResTypeController) Update() {
	var v preorder.ResType
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ResTypeId, "res_type_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"res_type_id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		err := preorder.UpdateResTypeById(&v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		ResTypeId  int64     `json:"res_type_id"`
		Modified   time.Time `json:"modified"`
	}{ResTypeId: v.ResTypeId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ResTypeController) Delete() {
	var v preorder.ResType
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ResTypeId, "res_type_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	err := preorder.DeleteResType(v.ResTypeId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		ResTypeId  int64  `json:"res_type_id"`
		Modified   time.Time `json:"modified"`
	}{ResTypeId: v.ResTypeId, Modified: time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON()
}

